import java.util.*;
import java.io.*;

public class SessionManager {
    private List<Session> sessions = new ArrayList<>();
    private static final String SESSION_FILE = "sessions.txt";
    private MovieManager movieManager;
    private List<Hall> halls;

    public SessionManager(MovieManager movieManager, List<Hall> halls) {
        this.movieManager = movieManager;
        this.halls = halls;
        loadSessionsFromFile();
    }

    // 从文件加载场次数据
    private void loadSessionsFromFile() {
        try (BufferedReader br = new BufferedReader(new FileReader(SESSION_FILE))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 5) {
                    Movie movie = movieManager.getMovieByName(parts[1]);
                    Hall hall = getHallByName(parts[2]);
                    if (movie != null && hall != null) {
                        Session session = new Session(parts[0], movie, hall, parts[3], Double.parseDouble(parts[4]));
                        sessions.add(session);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("场次数据文件不存在，将创建新文件");
        }
    }

    // 根据名称获取影厅
    private Hall getHallByName(String name) {
        for (Hall hall : halls) {
            if (hall.getName().equals(name)) {
                return hall;
            }
        }
        return null;
    }

    // 保存场次数据到文件
    private void saveSessionsToFile() {
        try (PrintWriter pw = new PrintWriter(new FileWriter(SESSION_FILE))) {
            for (Session session : sessions) {
                pw.println(session.getId() + "," + session.getMovie().getName() + "," +
                        session.getHall().getName() + "," + session.getTime() + "," + session.getPrice());
            }
        } catch (IOException e) {
            System.out.println("保存场次数据失败：" + e.getMessage());
        }
    }

    public boolean addSession(Session session) {
        sessions.add(session);
        saveSessionsToFile(); // 保存到文件
        return true;
    }

    public boolean removeSession(String id) {
        Iterator<Session> it = sessions.iterator();
        while (it.hasNext()) {
            Session s = it.next();
            if (s.getId().equals(id)) {
                it.remove();
                saveSessionsToFile(); // 保存到文件
                return true;
            }
        }
        return false;
    }

    public Session getSessionById(String id) {
        for (Session s : sessions) {
            if (s.getId().equals(id)) return s;
        }
        return null;
    }

    public List<Session> getAllSessions() {
        return sessions;
    }
}